﻿using Meow.Core.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Meow.Core.AssetManage;

public class MaterialCache : IAssetCache
{
    public MaterialDefine FallbackMaterialDefine { get; protected set; }
    public MatInstance FallbackMaterial { get; protected set; }

    internal readonly Dictionary<string, MaterialDefine> DefinesDictionary = new Dictionary<string, MaterialDefine>();
    internal readonly Dictionary<string, MatInstance> MaterialDictionary = new Dictionary<string, MatInstance>();

    public MaterialCache()
    {

    }

    public void Init()
    {
        FallbackMaterialDefine = new UnlitMaterial();
        FallbackMaterialDefine.LoadContent(Application.Content);

        var mat = new Mti_Basic3d(FallbackMaterialDefine);
        mat.MainTexture = Application.Content.Load<Texture2D>("CoreAssets/Img/rumya_labmeow");
        FallbackMaterial = mat;
    }

    public void LoadAndAddDefine(in string keyName, MaterialDefine materialDefine, ContentManager content)
    {
        materialDefine.LoadContent(content);
        DefinesDictionary.Add(keyName, materialDefine);
    }

    public void AddMaterial(in string keyName, MatInstance matInstance)
    {
        MaterialDictionary.Add(keyName, matInstance);
    }

    public MatInstance TryGetMaterial(in string keyName)
    {
        if (MaterialDictionary.TryGetValue(keyName, out MatInstance mat))
            return mat;

        return FallbackMaterial;
    }

    public void Dispose()
    {
        foreach(var (key,mat) in DefinesDictionary)
            mat.Dispose();

        foreach (var (key, mat) in MaterialDictionary)
            mat.Dispose();

        FallbackMaterial.Dispose();
        FallbackMaterialDefine.Dispose();
    }

    ///// <summary>
    ///// Create and Add a MatInstance in cache
    ///// </summary>
    ///// <param name="define"></param>
    ///// <param name=""></param>
    ///// <returns></returns>
    //public MatInstance CreateInstance(in string define, JObject matInfo)
    //{
    //    _CurrentIndex
    //}

    //public bool LoadMaterial(in string path)
    //{

    //}
}
